/* eslint-disable @typescript-eslint/no-use-before-define */
import React, {useState, useEffect, useRef} from "react";
import {Table, Select, Button, Input, Popconfirm, message, TableColumnType, Space, GetRef, notification} from "antd";
import {PlusCircleOutlined, MinusCircleOutlined, SearchOutlined} from "@ant-design/icons";
import type {TableProps} from "antd";
import {useSearchParams} from 'react-router-dom';

import ImportExcel from "./components/warehouseInformation/importExcel";
import ExportExcel from "./components/warehouseInformation/exportExcel";
import {WarehouseData} from "@/pages/New/components/projectOverview/selfGeneratedDataConstant";

interface DataType {
  key: React.Key;
  main: string;
  number: string;
  name: string;
  attribute: string;
  location: string;
  address: string;
  ownership: string;
  isImportant: boolean;
  note: string;
  editStatus?: boolean;
}

type DataIndex = keyof DataType;
type InputRef = GetRef<typeof Input>;

const WarehouseInformation: React.FC = () => {

  const [tableData, setTableData] = useState<DataType[]>([]);
  const [tempColumData, setTempColumData] = useState<DataType>();
  const [searchParams, setSearchParams] = useSearchParams();
  const searchInput = useRef<InputRef>(null);

  // 主体选项
  const mainOptions: { label: string; value: string }[] = [
    {
      label: "全部",
      value: "1",
    },
    {
      label: "仓库1",
      value: "2",
    },
    {
      label: "仓库2",
      value: "3",
    },
  ];

  // 仓库属性选项
  const attributeOptions: { label: string; value: string }[] = [
    {
      label: "生产仓库（车间）",
      value: "1",
    },
    {
      label: "存储仓库",
      value: "2",
    },
    {
      label: "第三方仓库",
      value: "3",
    },
  ];

  // 仓库位置选项
  const locationOptions: { label: string; value: string }[] = [
    {
      label: "产地附近",
      value: "1",
    },
    {
      label: "客户附近",
      value: "2",
    },
    {
      label: "其他",
      value: "3",
    },
  ];

  // 仓库权属选项
  const ownershipOptions: { label: string; value: string }[] = [
    {
      label: "自有",
      value: "1",
    },
    {
      label: "租用",
      value: "2",
    },
    {
      label: "第三方代管",
      value: "3",
    },
  ];

  // 是否重要仓库选项
  const importantOptions: { label: string; value: boolean }[] = [
    {
      label: "是",
      value: true,
    },
    {
      label: "否",
      value: false,
    },
  ];


  const getColumnSearchProps = (dataIndex: DataIndex, description: string): TableColumnType<DataType> => ({
    // 生成一个下拉过滤器
    /*
        setSelectedKeys: 用于设置当前选中的筛选项。
        selectedKeys: 当前选中的筛选项数组。
        confirm: 确认筛选操作的回调函数。
        clearFilters: 清除筛选条件的回调函数。
     */
    filterDropdown: ({setSelectedKeys, selectedKeys, confirm, clearFilters}) => (
      <form
        style={{padding: "1rem", display: "flex", gap: "0.5rem"}}
        onSubmit={(e) => {
          e.preventDefault();
          confirm();
        }}>
        <Input
          ref={searchInput}
          placeholder={description}
          value={selectedKeys[0]}
          onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
        />
        <Space>
          {/*通过 setSelectedKeys 更新筛选项，并调用 confirm() 来应用筛选*/}
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
          {/*清空筛选项、清除筛选条件并调用 confirm() 来刷新表格数据*/}
          <Button type="primary" htmlType="button" onClick={() => {
            setSelectedKeys([])
            // eslint-disable-next-line @typescript-eslint/no-unused-expressions
            clearFilters && clearFilters();
            confirm();
          }}>
            重置
          </Button>
        </Space>
      </form>
    ),
    filterIcon: (filtered: boolean) => (
      <SearchOutlined style={{color: filtered ? '#1677ff' : undefined, fontSize: '1.3em'}}/>
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        .toString()
        .toLowerCase()
        .includes((value as string).toLowerCase()),
  });

  // 定义表格列，TableProps<DataType>表示该表格组件接收数据类型为DataType
  const columns: TableProps<DataType>["columns"] = [
    {
      title: () => (
        <PlusCircleOutlined
          style={{color: "#1677ff", fontSize: 16}}
          onClick={() => {
            createColum();
          }}
        />
      ),
      dataIndex: "key",
      key: "key",
      align: "center",
      width: 50,
      render: (_, __, index) => {
        return (
          <Popconfirm
            title="确定删除吗？"
            onConfirm={() => {
              removeColum(index)
            }}
            onCancel={() => {
            }}
            okText="是"
            cancelText="否"
          >
            <MinusCircleOutlined style={{color: "#ff4d4f", fontSize: 16}}/>
          </Popconfirm>
        )
      },
    },
    {
      title: "序号",
      dataIndex: "key",
      key: "key",
      align: "center",
      width: 100,
    },
    {
      title: "主体",
      dataIndex: "main",
      key: "main",
      align: "center",
      width: 132,
      render: (_, {main, editStatus}) => {
        if (editStatus) {
          return (
            <Select
              defaultValue={main}
              style={{width: 100}}
              placeholder="请选择主体"
              onChange={(e) => {
                selectChange(e, "main");
              }}
              options={mainOptions}
            />
          );
        } else {
          return mainOptions.find((item) => item.value === main || item.label === main)?.label;
        }
      },
    },
    {
      title: "仓库编号",
      dataIndex: "number",
      key: "number",
      align: "center",
      width: 132,
      render: (_, {number, editStatus}) => {
        if (editStatus) {
          return (
            <Input
              defaultValue={number}
              style={{width: 100}}
              placeholder="请输入仓库编号"
              onChange={(e) => {
                inputChange(e, "number");
              }}
            />
          );
        } else {
          return <span>{number}</span>;
        }
      },
    },
    {
      title: "仓库名称",
      dataIndex: "name",
      key: "name",
      align: "center",
      width: 132,
      render: (_, {name, editStatus}) => {
        if (editStatus) {
          return (
            <Input
              defaultValue={name}
              style={{width: 100}}
              placeholder="请输入仓库名称"
              onChange={(e) => inputChange(e, "name")}
            />
          );
        } else {
          return <span>{name}</span>;
        }
      },
      ...getColumnSearchProps('name', '请输入仓库名称')
    },
    {
      title: "仓库属性",
      dataIndex: "attribute",
      key: "attribute",
      align: "center",
      width: 160,
      render: (_, {attribute, editStatus}) => {
        if (editStatus) {
          return (
            <Select
              defaultValue={attribute}
              style={{width: 100}}
              onChange={(e) => {
                selectChange(e, "attribute");
              }}
              options={attributeOptions}
            />
          );
        } else {
          return attributeOptions.find((item) => item.value === attribute || item.label === attribute)?.label;
        }
      },
    },
    {
      title: "仓库位置",
      dataIndex: "location",
      key: "location",
      align: "center",
      width: 132,
      render: (_, {location, editStatus}) => {
        if (editStatus) {
          return (
            <Select
              defaultValue={location}
              style={{width: 100}}
              onChange={(e) => {
                selectChange(e, "location");
              }}
              options={locationOptions}
            />
          );
        } else {
          return locationOptions.find((item) => item.value === location || item.label === location)?.label;
        }
      },
    },
    {
      title: "仓库地址",
      dataIndex: "address",
      key: "address",
      align: "center",
      width: 150,
      render: (_, {address, editStatus}) => {
        if (editStatus) {
          return (
            <Input
              defaultValue={address}
              style={{width: 100}}
              placeholder="请输入仓库地址"
              onChange={(e) => inputChange(e, "address")}
            />
          );
        } else {
          return <span>{address}</span>;
        }
      },
      ...getColumnSearchProps('address', '请输入仓库地址'),
    },
    {
      title: "仓库权属",
      dataIndex: "ownership",
      key: "ownership",
      align: "center",
      width: 132,
      render: (_, {ownership, editStatus}) => {
        if (editStatus) {
          return (
            <Select
              defaultValue={ownership}
              style={{width: 100}}
              onChange={(e) => {
                selectChange(e, "ownership");
              }}
              options={ownershipOptions}
            />
          );
        } else {
          return ownershipOptions.find((item) => item.value === ownership || item.label === ownership)?.label;
        }
      },
    },
    {
      title: "重要仓库",
      dataIndex: "isImportant",
      key: "isImportant",
      align: "center",
      width: 132,
      render: (_, {isImportant, editStatus}) => {
        if (editStatus) {
          return (
            <Select
              defaultValue={isImportant}
              style={{width: 100}}
              onChange={(e) => {
                selectChange(e, "isImportant");
              }}
              options={importantOptions}
            />
          );
        } else {
          return importantOptions.find((item) => item.value === isImportant)?.label || isImportant;
        }
      },
    },
    {
      title: "其他备注",
      dataIndex: "note",
      key: "note",
      align: "center",
      width: 132,
      render: (_, {note, editStatus}) => {
        if (editStatus) {
          return (
            <Input
              defaultValue={note}
              style={{width: 100}}
              placeholder="请输入其他备注"
              onChange={(e) => inputChange(e, "note")}
            />
          );
        } else {
          return <span>{note}</span>;
        }
      },
    },
    {
      title: "操作",
      dataIndex: "editStatus",
      key: "editStatus",
      align: "center",
      render: (_, {editStatus}, index) => {
        if (editStatus) {
          return (
            <div style={{display: "flex", justifyContent: "center"}}>
              <Button className="save_btn" size="small" type="link" onClick={() => saveEditChange(index)}>
                保存
              </Button>
              <Button size="small" type="link" onClick={() => {
                setTableData((prev) => {
                  const newData = [...prev];
                  newData[index] = tempColumData as DataType;
                  return newData;
                });
                setTempColumData(undefined);
                changeEditMode(false, index);
              }}>
                取消
              </Button>
            </div>
          );
        } else {
          return (
            <Button
              size="small"
              type="link"
              onClick={() => {
                setTempColumData(tableData[index]);
                changeEditMode(true, index);
              }}>
              编辑
            </Button>
          );
        }
      },
    },
  ];

  // 导入
  const handleDataUpload = (data: DataType[]) => {
    setTableData(data);
  };

  // 输入框变化
  const inputChange = (e: React.ChangeEvent<HTMLInputElement>, key: string) => {
    setTempColumData((prev) => {
      const newData: { [key: string]: any } = JSON.parse(JSON.stringify(prev));
      newData[key] = e.target.value;
      return newData as DataType;
    });
  };

  // 保存编辑元素
  const saveEditChange = (index: number) => {
    setTableData((prev) => {
      const newData = JSON.parse(JSON.stringify(tableData));
      newData[index] = tempColumData;
      if (newData[index].number === "") {
        console.log(123);
        newData[index].number = `CK-${formatNumber(index + 1)}`;
        console.log(newData[index].number);
      }
      newData[index].editStatus = false;
      return newData;
    });
  };

  // 格式化数字
  const formatNumber = (num: number): string => {
    return num.toString().padStart(3, "0");
  };

  // 切换编辑状态
  const changeEditMode = (editStatus: boolean, index: number) => {
    const newData = [...tableData];
    newData[index].editStatus = editStatus;
    setTableData(newData);
  };

  // 创建行
  const createColum = () => {
    let editing: boolean = false;
    for (let i = 0; i < tableData.length; i++) {
      if (tableData[i].editStatus) {
        editing = true;
        break;
      }
    }
    if (editing) return message.warning("请先保存当前数据");
    let data = JSON.parse(JSON.stringify(tableData));
    for (let i = 0; i < tableData.length; i++) {
      data[i].editStatus = false;
      data[i].key++;
    }
    const newData = {
      key: "1",
      main: "",
      number: "",
      name: "",
      attribute: "",
      location: "",
      address: "",
      ownership: "",
      isImportant: false,
      note: "",
      editStatus: true,
    };
    data.unshift(newData);
    setTableData(data);
    setTempColumData(newData);
  };

  // 删除行
  const removeColum = (inedx: number) => {
    const newData = [...tableData];
    newData.splice(inedx, 1);
    newData.forEach((item, index) => {
      item.key = index + 1;
    });
    setTableData(newData);
  };

  // 根据单体id获取仓库信息
  const getWarehouseDataById = (singleId: any) => {
    if (singleId === null) {
      return [];
    } else {
      let arrKeys = singleId.split('-');
      return WarehouseData[arrKeys[0]].data[arrKeys[1]].data
    }
  }

  // 警告提示
  const openNotification = () => {
    notification.open({
      message: (
        <p style={{color: 'red', fontSize: '18px'}}>消息提示</p>
      ),
      description: (
        <p style={{color: 'red'}}>请先选择一个项目单体</p>
      ),
      duration: 2.5, // 设置为2.5秒后消失
    });
  };

  // 初始化数据
  useEffect(() => {
    // 获取url传过来的id参数
    const singleId = searchParams.get('singleId');
    const data: DataType[] = getWarehouseDataById(singleId);
    console.log("仓库数据:", data);

    if (data.length === 0) {
      openNotification();
    }
    const updateData = data.map((item, index) => ({
      ...item,
      key: `${index + 1}`
    }))

    setTableData(updateData);
  }, []);

  /**
   * 下拉框变化
   */
  const selectChange = (event: string | boolean, key: string) => {
    setTempColumData((prev) => {
      const newData: { [key: string]: any } = JSON.parse(JSON.stringify(prev));
      newData[key] = event;
      return newData as DataType;
    });
  };

  return (
    <>
      <div>
        <div style={{display: "flex", justifyContent: "space-between", alignItems: "ceter", padding: "0.5rem 1rem"}}>
          <div style={{display: "flex", alignItems: "center", fontSize: "medium"}}>
            <h2>仓库信息表</h2>
          </div>
          <div style={{display: "flex", gap: "1rem"}}>
            <ImportExcel onDataUpload={handleDataUpload}/>
            <ExportExcel data={tableData}/>
          </div>
        </div>
        <Table pagination={false} columns={columns} dataSource={tableData} rowKey={(record) => record.key}/>
      </div>
    </>
  );
};

export default WarehouseInformation;
